package net.zhuike.novel.app.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import net.zhuike.novel.app.ZhuiKeApplication;
import net.zhuike.novel.app.bean.BookChapterBean;
import net.zhuike.novel.app.bean.BookSit;
import net.zhuike.novel.app.bean.ChapterInfoBean;
import net.zhuike.novel.app.bean.CollBookBean;
import net.zhuike.novel.app.bean.SitBean;
import net.zhuike.novel.app.bean.local.BookRepository;
import net.zhuike.novel.app.bean.local.SitRepository;
import net.zhuike.novel.app.ui.activity.ReadActivity;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.utils.BookManager;
import net.zhuike.novel.app.ui.utils.BrightnessUtils;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.utils.SiteHelper;
import net.zhuike.novel.app.ui.view.UeDialog;
import net.zhuike.novel.app.ui.view.page.TxtChapter;

import org.json.JSONException;
import org.json.JSONObject;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import framework.common.zanetwork.UeHttpUrl;
import framework.common.zanetwork.core.ResponseCallback;
import framework.log.LogUtils;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/11/8.
 *  不影响阅读体验，开启后台Service获取章节
 */

public class UpdateBookChaterService extends Service {
    /**
     * 是否继续运行线程
     */
    private boolean isRunning = true;
    private OkHttpClient mOkHttpClient;
    public String bookId;
    public String aId;
    private String contentUrl;
    String loadUrl;
    private List<BookSit.Chapters> mChapterSitList = new ArrayList<>();
    private List<BookChapterBean> mChapterList = new ArrayList<>();
    private SiteHelper helper;
    @Override
    public void onCreate() {
        super.onCreate();
    }
    private void getConfig() {
       SitBean bean= SitRepository.getInstance().getSit(bookId);
        if(bean!=null) {
            loadUrl = bean.getLoadUrl();
            getChapter(bean.getUrl());
        }
    }
    private void getChapter(String url) {
        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    String headers[] = null;
                    try {
                        com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                        if (restr.get("failed") != null) {
                        } else {
                            Message msg = new Message();
                            msg.obj = restr;
                            msg.what = 2;
                            handlers.sendMessage(msg);
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent!=null) {
            bookId = intent.getStringExtra("booId");
            aId = intent.getStringExtra("aid");
            if (isRunning) {
                getConfig();

            }
        }
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    try {
                        com.alibaba.fastjson.JSONObject restr = (com.alibaba.fastjson.JSONObject) msg.obj;
                        helper = new SiteHelper(restr);

                        String loadUrls;
                        if (loadUrl.indexOf("https") != -1) {
                            loadUrls = loadUrl;
                        } else {
                            if (loadUrl.indexOf("qidian.com") != -1) {
                                loadUrls = loadUrl.replace("http", "https");
                            } else {
                                loadUrls = loadUrl;
                            }
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Map<String, Object> contexts = new HashMap<String, Object>();
                                    contexts.put("aid", aId);
                                    contexts = helper.executeMulu(contexts, loadUrls);
                                    int i = 0;
                                    while (true) {
                                        Object[] chapters = (Object[]) contexts.get("chapters");//因目录获取经常不到，故循环获取
                                        if (chapters != null) {
                                            mChapterList.clear();
                                            for (Object o : chapters) {
                                                com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                                if (!cJson.getString("vip").equals("true")) {
                                                    BookChapterBean chapterBean = new BookChapterBean();
                                                    chapterBean.setBookId(bookId);
                                                    chapterBean.setLink(cJson.getString("url"));
                                                    chapterBean.setTitle(cJson.getString("name"));
                                                    mChapterList.add(chapterBean);
                                                }
                                            }
                                            BookRepository.getInstance()
                                                    .saveBookChaptersWithAsync(mChapterList);
                                            isRunning=false;
                                            stopSelf();
                                            break;
                                        }else{
                                            Thread.sleep(1000);
                                            i++;
                                        }
                                        if (i == 5) {
                                           break;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
}
